package utils

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"gitee.com/tainanleya/go_generate_tool/log"
	"io"
	"math/rand"
	"net/http"
	"os"
	"time"
)

func init() {
	rand.New(rand.NewSource(time.Now().UnixNano()))
}

const (
	TimeFormat = "2006-01-02 15:04:05"
	Str1Base   = "0123456789QWERTYUIOPASDFGHJKLZXCVBNM"
	Str2Base   = "qwertyuiopasdfghjklzxcvbnm0123456789QWERTYUIOPASDFGHJKLZXCVBNM"
)

func IsContainInt64(resource int64, target ...int64) bool {
	for _, item := range target {
		if resource == item {
			return true
		}
	}
	return false
}

func GeneratePassword(length int) string {
	var base = "qwertyuiopasdfghjklzxcvbnm0123456789QWERTYUIOPASDFGHJKLZXCVBNM"
	var result string
	for i := 0; i < length; i++ {
		index := rand.Intn(len(base))
		result += string(base[index])
	}
	return result
}

func GenerateBySourceStr(source string, length int) string {
	var result string
	for i := 0; i < length; i++ {
		index := rand.Intn(len(source))
		result += string(source[index])
	}
	return result
}

// GetInt64FromBytes 将bytes转为int64
func GetInt64FromBytes(cn []byte) int64 {
	if cn == nil || len(cn) < 8 {
		return 0
	}
	return int64(binary.LittleEndian.Uint64(cn))
}

func CloseAction(c io.Closer) {
	if c != nil {
		err := c.Close()
		if err != nil {
			log.Errorf("close conf err: %v", err)
		}
	}
}

// GetBytesForInt64 将int64转为bytes
func GetBytesForInt64(t uint64) []byte {
	cn := make([]byte, 8)
	binary.LittleEndian.PutUint64(cn, t)
	return cn
}

// GetPostData 从Post请求中获取数据
func GetPostData(r *http.Request) ([]byte, error) {
	//拿到数据就关闭掉
	defer CloseAction(r.Body)

	length := r.ContentLength
	var b bytes.Buffer
	b.Grow(int(length))
	_, err := io.Copy(&b, r.Body)
	if err != nil {
		return nil, err
	}
	return b.Bytes(), nil
}

// HasDuplicate 计算是否有重复的字符串
func HasDuplicate(arr []*string) bool {
	seen := make(map[string]bool)
	for _, s := range arr {
		if seen[*s] {
			return true
		}
		seen[*s] = true
	}
	return false
}

// CreateDirIfNotExist 没有则创建文件夹
func CreateDirIfNotExist(path string) error {
	// 检查路径是否为文件夹
	fileInfo, err := os.Stat(path)
	if os.IsNotExist(err) {
		// 路径不存在，创建文件夹
		err := os.MkdirAll(path, os.ModePerm)
		if err != nil {
			return fmt.Errorf("error creating directory: %s", err)
		}
		return nil // 创建成功，无错误
	} else if err != nil {
		return fmt.Errorf("error checking path: %s", err)
	} else {
		if fileInfo.IsDir() {
			return nil // 路径已存在且为文件夹，无错误
		} else {
			return fmt.Errorf("path is not a directory, it's a file")
		}
	}
}

// DeleteFile 文件存在则删除
func DeleteFile(filePath string) error {
	if filePath == "" {
		return nil
	}
	// 检查文件是否存在
	_, err := os.Stat(filePath)
	if os.IsNotExist(err) {
		return nil // 文件不存在，无错误
	} else if err != nil {
		return fmt.Errorf("error checking file: %s", err)
	}
	// 文件存在，删除它
	err = os.Remove(filePath)
	if err != nil {
		return fmt.Errorf("error deleting file: %s", err)
	}
	return nil // 删除成功，无错误
}
